//
//  NewsDetailViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/9/10.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import WebKit

class NewsDetailViewController: BaseViewController {
    
    var titleString = ""
    var url = ""
    var webView:WKWebView!
    var model:NewsModel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = titleString
        PKhud.show()
        let configuration = WKWebViewConfiguration()
        configuration.userContentController = WKUserContentController()
        configuration.userContentController.add(self, name: "ScriptMessageHandler")
        self.webView = WKWebView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight - (Utils.isIphoneX() ? 88 : 64)), configuration: configuration)
        self.webView.backgroundColor = UIColor.backgroundColor
        self.webView.allowsBackForwardNavigationGestures = true
        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
        self.webView.scrollView.delegate = self
        
        self.webView.load(URLRequest.init(url: URL.init(string: self.url)!))
        self.view.addSubview(self.webView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


extension NewsDetailViewController : WKScriptMessageHandler,WKUIDelegate,UIScrollViewDelegate,WKNavigationDelegate {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "ScriptMessageHandler" {
            let dic = message.body as! NSDictionary
            let arr = dic.allKeys as NSArray
            if arr.contains("comment"){
                let comment = dic["comment"] as! String
                self.commentNews(str: comment)
            }else if arr.contains("collection") {
                let isCollection = dic["collection"] as! Bool
                self.collectionNews(iscollection: isCollection)
            }else if arr.contains("share"){
                PKhud.showText(text: "功能开发中~")
            }
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        PKhud.hiden()
    }
    
}

extension NewsDetailViewController {
    func commentNews(str:String){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.articleComment.rawValue, parameters: ["articleId":self.model.id,"content":str]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: "评论成功~")
                let dic = ["avatar":Utils.getUserDefaulsFor(key: "storeImg") as! String,
                           "name":Utils.getUserDefaulsFor(key: "storeName") as! String,
                           "rating":str]
                let result = NSDictionary.init(dictionary: dic)
                let dicString = Utils.getJSONStringFromDictionary(dictionary: result)
                self.webView.evaluateJavaScript("succcessMes('\(dicString)')", completionHandler: { (_, error) in
                    print("success")
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    func collectionNews(iscollection:Bool){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.articleCollection.rawValue, parameters: ["id":self.model.id]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: result["data"] as! String)
                let str = Utils.getJSONStringFromDictionary(dictionary: NSDictionary.init(object: iscollection, forKey: NSString.init(string: "collection")))
                self.webView.evaluateJavaScript("favSuccess('\(str)')", completionHandler: { (_, error) in
                    print("success")
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
}





